﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using ARS.Common.Entitys;
using ARS.Common.Helper;
using ARS.Common.Service;
using ARS.Common.Service.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;

namespace ARS.Web.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DataController : ControllerBase
    {


        private DataRepository _DataRepo = new DataRepository(Program.appSetting.ArsDbStr);
        /// <summary>
        ///    /api/Data/FindEmailTemplates
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs("get", "post")]
        public PageList<EmailTemplate> FindEmailTemplates(string subject = null,bool? status=null, int pageindex = 1, int pagesize = 25)
        {
            //?groupname=&grouptype=&status=&pageindex=2&pagesize=20
            var result = _DataRepo.GetEmailTemplateAll(subject, status, pageindex, pagesize);
            return new PageList<EmailTemplate>() { Lists = result.Item1.ToList(), Page = new Page { PageIndex = 1, PageSize = int.MaxValue, TotalCount = result.Item2 } };
        }


        [AcceptVerbs("get", "post")]
        public BizResult<string> UpdateEmailTemplates(EmailTemplate model)
        {
            int result = 0;
            if (model.Id > 0)
            {
                result = _DataRepo.UpdateEmailTemplates(model);
            }
            else
            {
                result = _DataRepo.AddEmailTemplates(new[] { model });

            }
            return new BizResult<string>(result > 0, EnumBizCode.Success, "");
        }

        [AcceptVerbs("get", "post")]
        public BizResult<string> UpdatEmailSender(MailSender model)
        {
            int result = 0;
            if (model.Id > 0)
            {
                result = _DataRepo.UpdatEmailSender(model);
            }
            else
            {
                result = _DataRepo.AddEmailSender(model);
            }
            return new BizResult<string>(result > 0, EnumBizCode.Success, "");
        }
        [AcceptVerbs("get", "post")]
        public PageList<MailSender> FindMailSenderByPages(string name = null, int pageNumber = 1, int pageSize = 25)
        {
            var result = _DataRepo.GetMailSenderByPage(name, pageNumber, pageSize);
            return new PageList<MailSender>() { Lists = result.Item1.ToList(), Page = new Page { PageIndex = 1, PageSize = 50, TotalCount = result.Item2 } };
        }





        [AcceptVerbs("get", "post")]
        public BizResult<string> UpdateSqlInstance(SQlInstance model)
        {
            int result;
            if (model.Id > 0)
            {
                result = _DataRepo.UpdatSqlInstance(model);
            }
            else
            {
                result = _DataRepo.AddSQlInstance(model);
            }
            return new BizResult<string>(result > 0, EnumBizCode.Success, "");
        }


        [AcceptVerbs("get", "post")]
        public BizResult<string> GetData(string message)
        {

            return new BizResult<string>(message);
        }


        [AcceptVerbs("get", "post")]
        public ContentResult GetMetaDataMailSender()
        {
            var infos = _DataRepo.GetMailSenderAll().Select(x => new { key = x.Id, value = x.Name }).ToArray();

            string jscontent = "{}";
            if (infos.Length > 0)
            {
                jscontent = JsonHelper.ToJsonString(infos);
            }

            return Content($"var dr_mailSender={jscontent};", "text/javascript");
        }

        [AcceptVerbs("get", "post")]
        public ContentResult GetMetaDataSQlInstanceAll()
        {
            var infos = _DataRepo.GetSQlInstanceAll().Select(x => new { key = x.Id, value = x.Name, x.DbType }).ToArray();
            string jscontent = "{}";
            if (infos.Length > 0)
            {
                jscontent = JsonHelper.ToJsonString(infos);
            }

            return Content($"var dr_sqlinstance={jscontent};", "text/javascript");

        }
        [AcceptVerbs("get", "post")]
        public SQlInstance GetSQlInstanceById(int id)
        {
            var infos = _DataRepo.GetSQlInstance(id);
            infos.DBstring = StringHelper.DeEncrypt(infos.DBstring);
            return infos;
        }
        [AcceptVerbs("get", "post")]
        public PageList<SQlInstance> FindSQlInstanceByPages(string name = null, int pageNumber = 1, int pageSize = 25)
        {
            var result = _DataRepo.GetSQlInstanceByPage(name, pageNumber, pageSize);
            return new PageList<SQlInstance>() { Lists = result.Item1.ToList(), Page = new Page { PageIndex = 1, PageSize = 50, TotalCount = result.Item2 } };
        }

        [AcceptVerbs("get", "post")]
        public ContentResult getTestdata()
        {
            return Content("var xxxxy=12345;", "text/javascript");
        }

        /// <summary>
        /// 执行 邮件发送测试操作
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [AcceptVerbs("get", "post")]
        public BizResult<string> ExecEmailTest(CallModel model)
        {
            if (model == null || model.etId < 1)
            {
                return new BizResult<string>(false, EnumBizCode.Success, "请检查传入的参数");
            }
            // 直接调用服务 不产生日志
            //BuilderServices.Init(Program.appSetting.ArsDbStr);
            //BuilderServices.Run(model.etId, model.eParams);
            var _params = "";
            if (model == null)
            {
                return new BizResult<string>(false, EnumBizCode.Failed, "传递参数错误");
            }
            else
            {
                model.eParams.Add(new KeyValuePair<string, string>("etId", model.etId.ToString()));
                var _datas = model.eParams.Select(x =>
                {
                    return $"{x.Key}=\"{x.Value}\"" ;
                }).ToArray();
                _params = string.Join(" ", _datas);
            }
            // model.eParams.Select
            // 或者调用linux 的命令行
            //拼接参数

            var _execdll = $"{Program.appSetting.ExecPath}/ARS.Service.dll";
            var _logpath = $"{Program.appSetting.ExecPath}/logs/{model.etId}";

            if (!Directory.Exists(_logpath))
                Directory.CreateDirectory(_logpath);
            ExecCommondHelper.RunCommand("dotnet", $"{_execdll} {_params}>{_logpath}/auto_{DateTime.Now:yyyyMMdd_HH_mm_ss}.log");
            return new BizResult<string>(true, EnumBizCode.Success, "发送完成");
        }

        [AcceptVerbs("get", "post")]
        public string GetEmailtask_logs(DateTime start,DateTime end)
        {
          
            var data= JsonHelper.ToJsonString(_DataRepo.GetEmailtask_logs(start, end.AddDays(-1)));
            return data;

        }


        [AcceptVerbs("get", "post")]
        public BizResult<Person> GetPerson(Person info)
        {

            return new BizResult<Person>(info);
        }



    }
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime Createtime { get; set; }
        public bool Gender { get; set; }
    }


}